package controller

import (
	"strings"

	"github.com/gin-gonic/gin"
	"good.house/internal/dto/request"
	_ "good.house/internal/dto/response"
	"good.house/internal/service"
	innerValidator "good.house/internal/validator"
	"good.house/pkg/response"
)

type PublishController struct {
	service *service.PublishService
}

func NewPublishController(service *service.PublishService) *PublishController {
	return &PublishController{
		service: service,
	}
}

// @Summary 租房发布
// @Description 租房信息发布
// @Tags 发布
// @Accept  json
// @Produce  json
// @Param    data  body  request.PublishRequest  true  "发布参数"
// @Success 200 {object}  response.PublishResponse
// @Router /api/publish [post]
func (ctl *PublishController) Publish(ctx *gin.Context) {
	var req = &request.PublishRequest{}
	if err := ctx.ShouldBindBodyWithJSON(req); err != nil {
		if errs, ok := innerValidator.TranslateValidateError(err); ok {
			response.Error(ctx, strings.Join(errs, ";"))
			return
		}
		response.Error(ctx, err.Error())
		return
	}

	userId, exists := ctx.Get("userID")

	if !exists {
		response.Error(ctx, "服务内部错误")
		return
	}

	userId64 := userId.(int64)

	err := ctl.service.Publish(req, userId64)

	if err != nil {
		response.Error(ctx, err.Error())
		return
	}

	response.Success(ctx, "发布成功", nil)
}
